from django import forms
from django.core.exceptions import ValidationError
from app import models
from django.forms import ModelForm
from app.models import ToolInfo
import re


class LoginForm(forms.Form):
    # 将用户名字段改为邮箱字段
    email = forms.EmailField(label="邮箱", required=True)
    password = forms.CharField(label="密码", required=True, widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if not re.search(r'[A-Z]', password):
            raise ValidationError('密码必须包含至少一个大写字母')
        if not re.search(r'[a-z]', password):
            raise ValidationError('密码必须包含至少一个小写字母')
        if not re.search(r'\d', password):
            raise ValidationError('密码必须包含至少一个数字')
        return password


class ToolForm(ModelForm):
    class Meta:
        model = ToolInfo
        fields = '__all__'
        # 排除自动生成的字段，使用我们自定义的字段

    def clean_tool_number(self):
        tool_number = self.cleaned_data.get('tool_number')
        if self.instance.pk:  # 如果是更新操作
            if ToolInfo.objects.filter(tool_number=tool_number).exclude(pk=self.instance.pk).exists():
                raise ValidationError('该证书编号已存在')
        else:  # 如果是新增操作
            if ToolInfo.objects.filter(tool_number=tool_number).exists():
                raise ValidationError('该证书编号已存在')
        return tool_number

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'


from django import forms
from app.models import UserInfo


class UserForm(forms.ModelForm):
    # 添加确认密码字段
    confirm_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        required=True
    )

    class Meta:
        model = UserInfo
        fields = '__all__'
        # 从字段中排除confirm_password，因为它不是模型字段
        widgets = {
            'password': forms.PasswordInput,
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置角色默认值为用户(2)
        self.fields['role'].initial = 2
        # 设置权限字段默认值为False
        self.fields['kfv_cert_permission'].initial = False
        self.fields['kfc_cert_permission'].initial = False
        self.fields['dwy_cert_permission'].initial = False
        self.fields['ph_cert_permission'].initial = False
        self.fields['hma_cert_permission'].initial = False
        self.fields['lz_cert_permission'].initial = False
        self.fields['ddl_cert_permission'].initial = False
        
        # 修改:将隐藏字段的required属性设置为False
        if not kwargs.get('instance'):
            self.fields['role'].required = False
            self.fields['kfv_cert_permission'].required = False
            self.fields['kfc_cert_permission'].required = False
            self.fields['dwy_cert_permission'].required = False
            self.fields['ph_cert_permission'].required = False
            self.fields['hma_cert_permission'].required = False
            self.fields['lz_cert_permission'].required = False
            self.fields['ddl_cert_permission'].required = False
            self.fields['role'].widget = forms.HiddenInput()
            self.fields['kfv_cert_permission'].widget = forms.HiddenInput()
            self.fields['kfc_cert_permission'].widget = forms.HiddenInput()
            self.fields['dwy_cert_permission'].widget = forms.HiddenInput()
            self.fields['ph_cert_permission'].widget = forms.HiddenInput()
            self.fields['hma_cert_permission'].widget = forms.HiddenInput()
            self.fields['lz_cert_permission'].widget = forms.HiddenInput()
            self.fields['ddl_cert_permission'].widget = forms.HiddenInput()
        for name, field in self.fields.items():
            # 跳过confirm_password，因为已经单独设置了class属性
            if name != 'confirm_password' and field.widget.__class__ != forms.HiddenInput:
                field.widget.attrs['class'] = 'form-control'

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if not re.search(r'[A-Z]', password):
            raise ValidationError('密码必须包含至少一个大写字母')
        if not re.search(r'[a-z]', password):
            raise ValidationError('密码必须包含至少一个小写字母')
        if not re.search(r'\d', password):
            raise ValidationError('密码必须包含至少一个数字')
        return password
        
    # 添加clean_confirm_password方法验证两次密码输入是否一致
    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        
        if password and confirm_password and password != confirm_password:
            raise ValidationError('两次输入的密码不一致')
        return confirm_password
        
    # 在表单验证完成后，将确认密码从cleaned_data中删除
    def clean(self):
        cleaned_data = super().clean()
        # 删除confirm_password字段，因为它不是模型字段
        if 'confirm_password' in cleaned_data:
            del cleaned_data['confirm_password']
        
        # 为隐藏字段设置默认值，以防它们未在表单中提交
        if not self.instance.pk:  # 只在创建新用户时应用
            # 修改为始终设置默认值，无论字段是否在cleaned_data中
            cleaned_data.setdefault('role', 2)
            cleaned_data.setdefault('kfv_cert_permission', False)
            cleaned_data.setdefault('kfc_cert_permission', False)
            cleaned_data.setdefault('dwy_cert_permission', False)
            cleaned_data.setdefault('ph_cert_permission', False)
            cleaned_data.setdefault('hma_cert_permission', False)
            cleaned_data.setdefault('lz_cert_permission', False)
            cleaned_data.setdefault('ddl_cert_permission', False)
        return cleaned_data
